<template>
  <div class="ai-creater-container">
    <div class="input-box">
      <!-- 模型选择 -->
      <div class="models">
        <div class="items-grid" ref="itemsContainer">
          <div
            v-for="(item, index) in itemsIn"
            :key="item.template_id"
            class="tpl-item"
            :class="{ active: item.template_id === formData.template_id }"
            @click.stop="selectItem(item, index)">
            <!-- 第一行：图片 -->
            <div class="image-container">
              <img
                :src="item.img || 'https://placehold.co/60x60'"
                :alt="item.name"
                class="item-image" />
            </div>
          </div>
        </div>
        <div class="toggle-button">
          <div class="svg-box" @click.stop="toggleExpand" :class="{ expanded: isExpanded }">
            <svg
              width="16"
              height="16"
              viewBox="0 0 16 16"
              fill="none"
              xmlns="http://www.w3.org/2000/svg">
              <path d="M2 5L8 11L14 5" stroke="#7A7A7A" stroke-width="1.6" />
            </svg>
          </div>
        </div>
      </div>
      <!-- 输入框 -->
      <div class="textarea-container" v-if="formData.type === AIType.TEXT">
        <textarea
          id="prompt"
          v-model="formData.prompt"
          class="form-textarea"
          placeholder="Enter your prompt here..."
          resize="none"></textarea>
      </div>

      <div class="mt-[20px] ml-[16px] flex" v-else>
        <ImageUploader v-model="formData.url" />
        <p class="font-[500] text-[15px] text-[#7A7A7A] ml-[24px] mt-[16px]">
          This model requires no text input
        </p>
      </div>

      <!-- 按钮 -->
      <div class="prompt-bar">
        <div
          class="reselect-icon-container"
          @click="fetchCategoryPrompt"
          v-if="formData.type === AIType.TEXT">
          <SvgIcon class="ai-reselect-icon" name="ai-reselect" size="32" />
        </div>
        <button
          type="submit"
          class="submit-button"
          @click="handleSubmit"
          :disabled="!isFormValid || isSubmitting">
          Generate
        </button>
      </div>

      <!-- 悬浮层 -->
      <div class="layer" v-show="isExpanded">
        <div class="items-grid">
          <div
            v-for="(item, index) in items"
            :key="item.template_id"
            class="tpl-item"
            :class="{ active: item.template_id === formData.template_id }"
            @click.stop="selectItem(item, index)">
            <!-- 第一行：图片 -->
            <div class="image-container">
              <img
                :src="item.img || 'https://placehold.co/60x60'"
                :alt="item.name"
                class="item-image" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { AIType } from '@/types/ai';
  import { ref, onMounted, computed, watch, onUnmounted } from 'vue';
  import { AiAPI } from '@/api/ai';
  import type { ImageCategoryVO } from '@/types/ai';
  import { ElMessage } from 'element-plus';
  import ImageUploader from '@/views/home/components/ImageUploader.vue'; // 导入ImageUploader组件
  import router from '@/router/route';

  // 表单数据模型
  const formData = ref({
    type: AIType.TEXT, // 使用枚举替代硬编码的 1
    template_id: 0,
    prompt: '',
    url: '',
  });

  // 组件状态
  const isExpanded = ref(false); // 是否展开为多行网格
  const items = ref<ImageCategoryVO[]>([]); // 所有分类数据
  const itemToMoveIndex = ref<number | null>(null); // 存储需要移动的项的索引

  const itemsIn = computed(() => items.value.slice(0, 5));

  // 提交状态
  const isSubmitting = ref(false);
  // 表单验证
  const isFormValid = computed(() => {
    if (formData.value.template_id === null) {
      return false;
    }
    // 验证图片分类是否选择
    if (formData.value.type === AIType.IMAGE) {
      if (!formData.value.url) {
        return false;
      }
    }
    // 验证文本分类是否选择
    if (formData.value.type === AIType.TEXT) {
      if (!formData.value.prompt.trim().length) {
        return false;
      }
    }
    return true;
  });

  // 处理表单提交
  const handleSubmit = async () => {
    if (!isFormValid.value || isSubmitting.value) return;

    try {
      isSubmitting.value = true;

      const params = {
        gen_type: formData.value.type,
        template_id: formData.value.template_id,
        prompt_text: formData.value.type === AIType.TEXT ? formData.value.prompt : '',
        img: formData.value.type === AIType.IMAGE ? formData.value.url : '',
      };

      await AiAPI.generate(params);

      ElMessage.success('Successfully created design character');
      router.push({
        path: '/generator',
      });
    } catch (error: any) {
      const { code } = error.response.data || {};
      if (code === 100201) {
        ElMessage.warning('Too many tasks submitted. Please try again later.');
      }
    } finally {
      setTimeout(() => {
        isSubmitting.value = false;
      }, 1000);
    }
  };

  // 获取分类数据
  const fetchCategories = async () => {
    try {
      const response = await AiAPI.getImageCategorys({ gen_type: 0 });
      if (response.data && Array.isArray(response.data)) {
        items.value = response.data;
        // 默认选中第一个
        if (items.value.length > 0) {
          // 使用 formData.template_id 替代 activeId
          formData.value.template_id = items.value[0].template_id;
          formData.value.type = items.value[0].gen_type;
        }
      }
    } catch (error) {
      console.error('获取图片分类失败:', error);
    }
  };

  // 处理展开/收起切换
  const toggleExpand = () => {
    // 如果当前是展开状态，且有需要移动的项，则在收起前处理
    if (isExpanded.value && itemToMoveIndex.value !== null) {
      const index = itemToMoveIndex.value;
      const selectedItem = items.value[index];
      items.value.splice(index, 1); // 从原位置移除
      items.value.unshift(selectedItem); // 添加到数组开头
      itemToMoveIndex.value = null; // 重置
    }
    isExpanded.value = !isExpanded.value;
  };

  // 点击非浮层区域时隐藏浮层
  const handleClickOutside = (event: MouseEvent) => {
    const layerElement = document.querySelector('.layer');
    const toggleButton = document.querySelector('.toggle-button');

    // 如果浮层是展开状态，且点击目标不是浮层本身、切换按钮或它们的子元素
    if (isExpanded.value && layerElement && toggleButton) {
      const isClickOnLayer = layerElement.contains(event.target as Node);
      const isClickOnToggleButton = toggleButton.contains(event.target as Node);

      if (!isClickOnLayer && !isClickOnToggleButton) {
        toggleExpand();
      }
    }
  };

  // 组件挂载时添加全局点击事件监听
  onMounted(() => {
    fetchCategories();
    document.addEventListener('click', handleClickOutside);
  });

  // 组件卸载时移除全局点击事件监听
  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
  });

  // 处理选中项
  const selectItem = (item: ImageCategoryVO, index: number) => {
    // 移除 activeId 的设置
    // 第5个之后的选项，只记录需要移动的索引，不立即处理
    if (index > 4) {
      itemToMoveIndex.value = index;
    } else {
      itemToMoveIndex.value = null; // 如果选择的是前5个，重置
    }

    // 设置formData.template_id
    formData.value.template_id = item.template_id;
    formData.value.type = item.gen_type;
  };

  // 根据当前选中的分类获取推荐的 prompt
  const fetchCategoryPrompt = async () => {
    if (formData.value.type !== AIType.TEXT) return;
    const response = await AiAPI.getCategoryPrompt({
      template_id: formData.value.template_id,
    });
    formData.value.prompt = response.data.prompt || '';
  };

  watch(
    () => formData.value.template_id,
    (newTemplateId) => {
      if (newTemplateId) {
        if (formData.value.type === AIType.TEXT) {
          fetchCategoryPrompt();
        }
      }
    }
  );

  // 组件挂载时获取数据
  onMounted(() => {
    fetchCategories();
  });
</script>

<style scoped lang="scss">
  .ai-creater-container {
    padding: 16px;
    width: 43%;
    min-width: 490px;
    flex-shrink: 0;
    border-radius: 8px;
    background: linear-gradient(270deg, #fff3e8 0%, #ffeadf 100%);
    height: 320px;
    position: relative;
  }
  .layer {
    position: absolute;
    top: 0;
    left: 0;
    width: 86%;
    padding: 16px;
    height: 120%;
    border-radius: 8px;
    background: white;
    z-index: 99;
    /* 浮层卡片投影 */
    box-shadow: 0 2px 24px 0 rgba(100, 130, 159, 0.25);
    .items-grid {
      display: grid;
      gap: 16px;
      grid-template-columns: repeat(5, 1fr);
      overflow: auto;
      max-height: 100%;
    }
  }
  .input-box {
    padding: 16px;
    height: 100%;
    border-radius: 8px;
    background: white;
    display: flex;
    flex-direction: column;
    position: relative;
  }
  .textarea-container {
    position: relative;
    flex: 1;
    padding-bottom: 8px;
    .form-textarea {
      width: 100%;
      padding: 8px 0px;
      border-radius: 8px;
      resize: none;
      outline: none;
      background: white;
      font-weight: 400;
      font-size: 14px;
      height: 100%;
      color: #222222;
      /* 添加占位符文本样式 */
      &::placeholder {
        color: #7a7a7a; /* 与输入文本相同的颜色 */
      }
    }
  }

  .prompt-bar {
    position: absolute;
    bottom: 16px;
    right: 16px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .char-counter {
      font-size: 14px;
      color: #7a7a7a;
      padding-right: 16px;
    }

    .reselect-icon-container {
      padding: 2px;
      border-radius: 4px;
      cursor: pointer;
      svg {
        transition: all 0.3s ease;
      }
      &:hover {
        background: #ededed;
        svg {
          transform: rotate(30deg) scale(1.05);
        }
      }
      &:active {
        background: #222222;
      }
    }
  }

  // 模型选择相关样式
  .models {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .items-grid {
      width: 86%;
      display: grid;
      gap: 16px;
      grid-template-columns: repeat(5, 1fr);
    }

    .toggle-button {
      padding-right: 16px;
      .svg-box {
        display: flex;
        width: 32px;
        height: 32px;
        justify-content: center;
        align-items: center;
        background: #ededed;
        cursor: pointer;
        border-radius: 4px;

        &:hover {
          background: #e1e2e3;
        }
        svg {
          transition: all 0.3s ease;
        }
        &.expanded {
          svg {
            transform: rotate(180deg);
          }
        }
      }
    }
  }

  .tpl-item {
    max-height: 100px;
    cursor: pointer;
    border-radius: 8px;
    text-align: center;
    transition: all 0.3s ease;
    height: 100%;
    box-sizing: border-box;
    aspect-ratio: 1 / 1;
    flex-shrink: 0;
    &.active {
      .name {
        color: #f76b1b;
      }
      .image-container {
        border-color: #f76b1b;
        &:hover {
          border-color: #f76b1b;
        }
      }
    }

    .image-container {
      width: 100%;
      height: 100%;
      overflow: hidden;
      border-radius: 8px;
      background-color: #f8f8f8;
      flex-shrink: 0;
      border: 2px solid #ededed;
      margin-bottom: 8px;
      transition: all 0.3s ease;
      &:hover {
        border-color: #cbcbcb;
      }
      .item-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .name {
        font-size: 14px;
        font-weight: 500;
        color: #222222;
      }
    }
  }

  .submit-button {
    margin-left: 12px;
    height: 40px;
    line-height: 40px;
    padding: 0px 24px;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 700;
    cursor: pointer;
    background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);

    &:disabled {
      background: #ccc;
      pointer-events: none;
    }
    &:hover:not(:disabled) {
      background: linear-gradient(90deg, #f78647 0%, #e1603d 100%);
    }
  }
</style>
